﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OpenId.RelyingParty;
using System.Web.Security;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.Messaging;
using Microsoft.WindowsAzure;
using FeedReader.Shared.Data;

namespace MvcFrontEnd.Controllers
{
    public class GoogleController : Controller
    {
        public static OpenIdRelyingParty openid = new OpenIdRelyingParty();
        static CloudStorageAccount acc = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        public static UsersDataSource userstable = new UsersDataSource(acc);
        //
        // GET: /Google/

        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/User/Login?ReturnUrl=Index");
            }

            return View("Index");
        }
        public ActionResult Logout()
        {

            FormsAuthentication.SignOut();
            return View("Index");
        }

        public ActionResult Login()
        {
            return RedirectToAction("Authenticate");
        }
        public ActionResult Authenticate()
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse("https://www.google.com/accounts/o8/id", out id))
                {
                    try
                    {
                        return openid.CreateRequest("https://www.google.com/accounts/o8/id").RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData["Message"] = ex.Message;
                        return View("Login");
                    }
                }
                else
                {
                    ViewData["Message"] = "Invalid identifier";
                    return View("Login");
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        
                        FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                        string id = response.ClaimedIdentifier.ToString();
                        var results =userstable.Select(id);
                        try
                        {
                            if (results.Count() > 0)
                            {
                                Session["FriendlyIdentifier"] = results.ElementAt(0).UserFName;
                                return RedirectToAction("Index", "Home", results.ElementAt(0).UserID);
                            }
                            else
                            {
                                UsersDataModel user = new UsersDataModel();
                                user.UserID = id;
                                user.Type = "Standard";
                                userstable.Insert(user);

                                return RedirectToAction("Register");
                            }
                        }
                        catch
                        {
                            UsersDataModel user = new UsersDataModel();
                            user.UserID = id;
                            user.Type = "Standard";
                            userstable.Insert(user);

                            return RedirectToAction("Register");

                        }
                    case AuthenticationStatus.Canceled:
                        ViewData["Message"] = "Canceled at provider";
                        return View("Login");
                    case AuthenticationStatus.Failed:
                        ViewData["Message"] = response.Exception.Message;
                        return View("Login");
                }

            }
            return new EmptyResult();
        }

    }
}
